# -*- coding: utf-8  -*-
#!/usr/local/bin/python

__author__ = 'yaojian'

import xml.etree.cElementTree as EI
from django.utils import simplejson

def elem_to_internal(elem, strip = 1):
    d = {}
    for key, value in elem.attrib.items():
        d['@' + key] = value

    for subelem in elem:
        v = elem_to_internal(subelem, strip = strip)
        tag = subelem.tag
        value = v[tag]
        try:
            d[tag].append(value)
        except AttributeError:
            d[tag] = [d[tag], value]
        except KeyError:
            d[tag] = value
    text = elem.text
    tail = elem.tail
    if strip:
        if text: text = text.strip()
        if tail: tail = tail.strip()

    if tail:
        d['#tail'] = tail

    if d:
        if text: d["#text"] = text
    else:
        d = text or ""
    return {elem.tag : d}


def elem2json(elem, strip = 1):
    if hasattr(elem, 'getroot'):
        elem = elem.getroot()
    return simplejson.dumps(elem_to_internal(elem,strip = strip))

def xml2json(xmlstring, strip = 1):
    elem = EI.fromstring(xmlstring.encode("utf-8"))
    return elem2json(elem, strip = strip)

